<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold text-gray-900 mb-4">实时录音</h1>
        <p class="text-xl text-gray-600">开始录音，AI将自动转录并生成会议纪要</p>
      </div>

      <div class="max-w-4xl mx-auto">
        <!-- Meeting Info -->
        <div class="card p-6 mb-8">
          <div class="flex items-center gap-4 mb-6">
            <div class="w-12 h-12 bg-gradient-to-r from-red-500 to-pink-600 rounded-xl flex items-center justify-center">
              <Mic class="w-6 h-6 text-white" />
            </div>
            <div>
              <h2 class="text-xl font-semibold text-gray-900">新会议</h2>
              <p class="text-gray-600">填写会议信息</p>
            </div>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                会议标题 *
              </label>
              <input
                v-model="meetingInfo.title"
                type="text"
                class="input-field"
                placeholder="输入会议标题..."
                :disabled="isRecording || isProcessing"
              />
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                会议描述（可选）
              </label>
              <input
                v-model="meetingInfo.description"
                type="text"
                class="input-field"
                placeholder="输入会议描述..."
                :disabled="isRecording || isProcessing"
              />
            </div>
          </div>
        </div>

        <!-- Recording Section -->
        <div class="card p-8 mb-8">
          <!-- Recording Interface -->
          <div v-if="!isProcessing" class="text-center">
            <!-- Timer Display -->
            <div v-if="isRecording || recordingDuration > 0" class="mb-8">
              <div class="text-5xl font-mono font-bold text-gray-900 mb-2">
                {{ formatTime(recordingDuration) }}
              </div>
              <div class="text-gray-600">
                {{ recordingStatus === 'recording' ? '正在录音...' : '录音已暂停' }}
              </div>
            </div>

            <!-- Recording Controls -->
            <div class="flex items-center justify-center gap-4 mb-8">
              <!-- Start Recording -->
              <button
                v-if="!isRecording && recordingDuration === 0"
                @click="startRecording"
                :disabled="!meetingInfo.title.trim()"
                class="btn-primary bg-red-600 hover:bg-red-700 px-8 py-4 rounded-full flex items-center gap-3 text-lg"
              >
                <Mic class="w-6 h-6" />
                开始录音
              </button>

              <!-- Stop Recording -->
              <button
                v-if="isRecording"
                @click="stopRecording"
                class="bg-gray-800 hover:bg-gray-900 text-white px-8 py-4 rounded-full flex items-center gap-3 text-lg transition-colors"
              >
                <Square class="w-6 h-6" />
                停止录音
              </button>

              <!-- Pause/Resume -->
              <button
                v-if="isRecording && !isPaused"
                @click="pauseRecording"
                class="bg-yellow-500 hover:bg-yellow-600 text-white px-6 py-4 rounded-full flex items-center gap-3 transition-colors"
              >
                <Pause class="w-6 h-6" />
                暂停
              </button>

              <button
                v-if="isRecording && isPaused"
                @click="resumeRecording"
                class="bg-green-500 hover:bg-green-600 text-white px-6 py-4 rounded-full flex items-center gap-3 transition-colors"
              >
                <Play class="w-6 h-6" />
                继续
              </button>
            </div>

            <!-- Audio Level Indicator -->
            <div v-if="isRecording" class="mb-8">
              <div class="h-2 bg-gray-200 rounded-full overflow-hidden">
                <div
                  class="h-full bg-red-500 rounded-full transition-all duration-100"
                  :style="{ width: audioLevel + '%' }"
                ></div>
              </div>
              <p class="text-sm text-gray-500 mt-2">音量指示器</p>
            </div>
          </div>

          <!-- Processing State -->
          <div v-else class="text-center py-12">
            <div class="mb-8">
              <div class="text-3xl font-bold text-gray-900 mb-4">
                处理进度 {{ processingProgress }}%
              </div>
              <div class="w-full bg-gray-200 rounded-full h-3 mb-4">
                <div
                  class="bg-gradient-to-r from-blue-500 to-purple-600 h-3 rounded-full transition-all duration-500"
                  :style="{ width: processingProgress + '%' }"
                ></div>
              </div>
              <p class="text-gray-600">{{ processingStatus }}</p>
            </div>

            <!-- Processing Steps -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
              <div
                v-for="(step, index) in processingSteps"
                :key="index"
                class="p-4 rounded-lg border transition-all"
                :class="step.completed ? 'bg-green-50 border-green-200' : 'bg-gray-50 border-gray-200'"
              >
                <div class="flex items-center gap-3">
                  <div
                    class="w-8 h-8 rounded-full flex items-center justify-center"
                    :class="step.completed ? 'bg-green-600 text-white' : 'bg-gray-300 text-gray-600'"
                  >
                    <Check v-if="step.completed" class="w-4 h-4" />
                    <span v-else class="text-sm">{{ index + 1 }}</span>
                  </div>
                  <div class="text-left">
                    <p class="font-medium text-gray-900">{{ step.title }}</p>
                    <p class="text-sm text-gray-600">{{ step.description }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Instructions -->
        <div class="card p-6 bg-blue-50 border-blue-200">
          <div class="flex items-start gap-4">
            <div class="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center flex-shrink-0">
              <Info class="w-5 h-5 text-white" />
            </div>
            <div>
              <h3 class="font-semibold text-gray-900 mb-2">录音说明</h3>
              <ul class="text-sm text-gray-700 space-y-1">
                <li>• 请确保麦克风权限已开启</li>
                <li>• 录音完成后系统将自动转录并生成会议纪要</li>
                <li>• 处理完成后将自动跳转到历史记录页面</li>
                <li>• 整个过程可能需要5-10分钟，请耐心等待</li>
              </ul>
            </div>
          </div>
        </div>
      </div>

      <!-- Progress Modal (for detailed progress) -->
      <ProgressModal
        v-if="showProgressModal"
        type="transcribing"
        :title="progressTitle"
        :description="progressDescription"
        :progress="processingProgress"
        :steps="progressSteps"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMeetingStore } from '@/stores/meeting'
import { transcribeAudio, generateMinutes } from '@/services/api'
import ProgressModal from '@/components/ui/ProgressModal.vue'
import {
  Mic,
  Square,
  Pause,
  Play,
  Check,
  Info
} from 'lucide-vue-next'

const router = useRouter()
const meetingStore = useMeetingStore()

// Meeting Info
const meetingInfo = ref({
  title: '',
  description: ''
})

// Recording State
const isRecording = ref(false)
const isPaused = ref(false)
const isProcessing = ref(false)
const recordingDuration = ref(0)
const recordingStatus = ref('idle')
const audioLevel = ref(0)
const processingProgress = ref(0)
const processingStatus = ref('')
const showProgressModal = ref(false)

// Processing Steps
const processingSteps = ref([
  {
    title: '录音完成',
    description: '音频录制完成',
    completed: false
  },
  {
    title: '创建会议',
    description: '正在创建会议记录',
    completed: false
  },
  {
    title: 'AI转录',
    description: '正在使用Whisper AI转录音频',
    completed: false
  },
  {
    title: '生成纪要',
    description: '正在分析内容并生成会议纪要',
    completed: false
  }
])

// Progress Modal State
const progressTitle = ref('')
const progressDescription = ref('')
const progressSteps = ref<{ name: string; completed: boolean }[]>([])

// Media Recorder
let mediaRecorder: MediaRecorder | null = null
let audioChunks: Blob[] = []
let timerInterval: NodeJS.Timeout | null = null
let audioContext: AudioContext | null = null
let analyser: AnalyserNode | null = null
let microphone: MediaStreamAudioSourceNode | null = null
let rafId: number | null = null

// Methods
const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })

    // Setup Media Recorder
    mediaRecorder = new MediaRecorder(stream)
    audioChunks = []

    mediaRecorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        audioChunks.push(event.data)
      }
    }

    mediaRecorder.onstop = async () => {
      const audioBlob = new Blob(audioChunks, { type: 'audio/wav' })
      await processRecording(audioBlob)
    }

    // Setup Audio Context for level monitoring
    audioContext = new AudioContext()
    analyser = audioContext.createAnalyser()
    microphone = audioContext.createMediaStreamSource(stream)
    microphone.connect(analyser)
    analyser.fftSize = 256

    // Start recording
    mediaRecorder.start()
    isRecording.value = true
    isPaused.value = false
    recordingStatus.value = 'recording'
    recordingDuration.value = 0

    // Start timer
    timerInterval = setInterval(() => {
      recordingDuration.value++
    }, 1000)

    // Start audio level monitoring
    updateAudioLevel()

  } catch (error) {
    console.error('Failed to start recording:', error)
    alert('无法访问麦克风，请检查权限设置')
  }
}

const stopRecording = () => {
  if (mediaRecorder && mediaRecorder.state !== 'inactive') {
    mediaRecorder.stop()
    mediaRecorder.stream.getTracks().forEach(track => track.stop())

    isRecording.value = false
    isPaused.value = false
    recordingStatus.value = 'processing'

    if (timerInterval) {
      clearInterval(timerInterval)
      timerInterval = null
    }

    if (rafId) {
      cancelAnimationFrame(rafId)
      rafId = null
    }

    if (audioContext) {
      audioContext.close()
      audioContext = null
    }
  }
}

const pauseRecording = () => {
  if (mediaRecorder && mediaRecorder.state === 'recording') {
    mediaRecorder.pause()
    isPaused.value = true
    recordingStatus.value = 'paused'

    if (timerInterval) {
      clearInterval(timerInterval)
      timerInterval = null
    }
  }
}

const resumeRecording = () => {
  if (mediaRecorder && mediaRecorder.state === 'paused') {
    mediaRecorder.resume()
    isPaused.value = false
    recordingStatus.value = 'recording'

    timerInterval = setInterval(() => {
      recordingDuration.value++
    }, 1000)
  }
}

const updateAudioLevel = () => {
  if (analyser && isRecording.value && !isPaused.value) {
    const dataArray = new Uint8Array(analyser.frequencyBinCount)
    analyser.getByteFrequencyData(dataArray)

    const average = dataArray.reduce((sum, value) => sum + value, 0) / dataArray.length
    audioLevel.value = Math.min(100, (average / 128) * 100)

    rafId = requestAnimationFrame(updateAudioLevel)
  }
}

const processRecording = async (audioBlob: Blob) => {
  try {
    isProcessing.value = true
    processingProgress.value = 0
    processingStatus.value = '开始处理录音...'

    // Step 1: 录音完成
    processingSteps.value[0].completed = true
    processingProgress.value = 5
    processingStatus.value = '录音完成，正在创建会议...'

    // Step 2: 创建会议
    progressTitle.value = '创建会议'
    progressDescription.value = '正在创建新的会议记录...'
    progressSteps.value = [
      { name: '验证会议信息', completed: true },
      { name: '创建会议记录', completed: false },
      { name: '准备音频处理', completed: false }
    ]

    const meetingResponse = await meetingStore.createNewMeeting({
      title: meetingInfo.value.title,
      description: meetingInfo.value.description
    })

    // 获取meeting_id，支持不同的响应格式
    const meetingId = meetingResponse.meeting?.id || meetingResponse.meeting_id || meetingResponse.id

    processingSteps.value[1].completed = true
    processingProgress.value = 15
    processingStatus.value = '会议创建完成，开始AI转录...'

    // Step 3: 转录音频
    progressTitle.value = 'AI智能转录'
    progressDescription.value = '正在使用Whisper AI转录音频内容...'
    progressSteps.value = [
      { name: '音频预处理', completed: true },
      { name: 'Whisper模型推理', completed: false },
      { name: '转录结果优化', completed: false }
    ]

    const file = new File([audioBlob], 'recording.wav', { type: 'audio/wav' })
    await transcribeAudio(
      file,
      meetingId,
      (progress) => {
        const overallProgress = 15 + (progress * 0.45)
        processingProgress.value = Math.floor(overallProgress)
        processingStatus.value = `转录进度: ${progress}%`
      }
    )

    processingSteps.value[2].completed = true
    processingProgress.value = 65
    processingStatus.value = '转录完成，开始生成会议纪要...'

    // Step 4: 生成会议纪要
    progressTitle.value = 'AI智能生成纪要'
    progressDescription.value = '正在分析转录内容并生成结构化会议纪要...'
    progressSteps.value = [
      { name: '内容分段总结', completed: true },
      { name: '会议纪要生成', completed: false },
      { name: '格式优化处理', completed: false }
    ]

    await generateMinutes(
      meetingId,
      '标准会议纪要',
      (progress: number) => {
        const overallProgress = 65 + (progress * 0.30)
        processingProgress.value = Math.floor(overallProgress)
        processingStatus.value = `生成进度: ${progress}%`
      }
    )

    // Complete
    processingSteps.value[3].completed = true
    processingProgress.value = 100
    processingStatus.value = '处理完成！正在跳转...'

    // Update meeting status
    meetingStore.updateMeetingStatus(meetingId, 'completed')

    // Wait a moment then redirect
    setTimeout(() => {
      router.push('/history')
    }, 2000)

  } catch (error) {
    console.error('Failed to process recording:', error)
    processingStatus.value = '处理失败，请重试'
    isProcessing.value = false
  }
}

const formatTime = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// Lifecycle
onMounted(() => {
  // Check for microphone support
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    alert('您的浏览器不支持录音功能')
  }
})

onUnmounted(() => {
  // Cleanup
  if (timerInterval) {
    clearInterval(timerInterval)
  }
  if (rafId) {
    cancelAnimationFrame(rafId)
  }
  if (audioContext) {
    audioContext.close()
  }
  if (mediaRecorder && mediaRecorder.state !== 'inactive') {
    mediaRecorder.stop()
    mediaRecorder.stream.getTracks().forEach(track => track.stop())
  }
})
</script>